/**
 * @Description: 预览大图
 * @Author: ZhangHan
 * @Date: 2025-07-30 17:55:15
 * @param {string} src 图片地址
 * @param {Array<any>} list 图片列表
 */
export const handlePreviewImage = (src: string, list: Array<any>) => {
  const srcArr: Array<string> = [];
  list?.map((v) => {
    srcArr.push(v);
  });

  uni.previewImage({
    current: src,
    urls: srcArr,
  });
};

/**
 * @Description: 大型json字符串转换解决小程序直接json.parse报错
 * @Author: ZhangHan
 * @Date: 2025-08-01 11:26:07
 * @param {string} jsonStr 超大型json字符串  "{}" 类型
 */
export const bigJsonParse = (jsonStr: string) => {
  // 假设 bigJsonStr 是超长的 JSON 字符串
  const chunkSize = 1024 * 1024 * 2; // 2MB 一个块
  const chunks: any = [];

  for (let i = 0; i < jsonStr.length; i += chunkSize) {
    chunks.push(jsonStr.slice(i, i + chunkSize));
  }

  console.log(chunks);

  // 尝试逐块解析（适用于流式 JSON）
  let parsedData = {};
  chunks.forEach((chunk: any) => {
    try {
      const partialData = JSON.parse(chunk);
      parsedData = { ...parsedData, ...partialData };
    } catch (e) {
      console.error("解析失败:", e);
    }
  });

  console.log(parsedData);
  return parsedData;
};

/**
 * @Description: 点击复制文本,并设置剪切板
 * @Author: ZhangHan
 * @Date: 2025-07-30 17:57:16
 * @param {string} text 文本内容
 */
export const copyText = (text: string) => {
  uni.setClipboardData({
    data: text,
    success() {
      uni.setClipboardData({
        data: text,
        success: function () {
          console.log("success");
        },
      });
    },
  });
};

/**
 * @Description: 身份证脱敏
 * @Author: ZhangHan
 * @Date: 2025-07-30 17:59:07
 * @param {string} value 身份证号
 * @returns {string} 脱敏后的身份证号
 */
// 身份证脱敏
export const getCardId = (value: string): string => {
  if (value && value.length >= 18) {
    return `${value.substr(0, 10)}****${value.substr(value.length - 4, 4)}`;
  }
  if (!value) {
    return "-";
  }
  return value;
};

// 获取bmi 对应文字
export const getBmiColor = (bmi: number) => {
  let res;
  if (bmi < 18.5) {
    res = {
      text: "偏瘦",
      color: "gray",
    };
  }

  if (bmi >= 18.5 && bmi < 24.0) {
    res = {
      text: "正常",
      color: "#52c41a",
    };
  }

  if (bmi >= 24.0 && bmi < 28.0) {
    res = {
      text: "超重",
      color: "orange",
    };
  }

  if (bmi >= 28.0) {
    res = {
      text: "肥胖",
      color: "red",
    };
  }

  return res;
};

//节流

export function throttle<T>(
  func: (this: T, ...args: any[]) => any,
  wait: number
) {
  let lastTime = 0;
  return function (this: T, ...args: any[]) {
    const now = Date.now();
    if (now - lastTime >= wait) {
      func.apply(this, args);
      lastTime = now;
    }
  };
}

// H5下载方法
export function downloadImageH5(imageUrl: string) {
  const a = document.createElement("a");
  a.href = imageUrl;
  a.download = "image_" + new Date().getTime() + ".jpg"; // 设置下载文件名
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);

  uni.showToast({
    title: "图片下载中",
    icon: "none",
    duration: 1000,
  });
}

//uni微信小程序下载图片
export const downloadPic = (imageTempPath: any) => {
  uni.getSetting({
    complete(res) {
      console.log(res.authSetting, "授权信息");
      if (res.authSetting["scope.writePhotosAlbum"]) {
        console.log(res.authSetting["scope.writePhotosAlbum"], "是否已经授权");
        uni.getImageInfo({
          src: imageTempPath,
          fail(error) {
            console.log(error);
          },
          success(result) {
            console.log(result);
            if (result.path) {
              uni
                .saveImageToPhotosAlbum({
                  filePath: result.path,
                })
                .then((getImageInfoResult) => {
                  if (
                    getImageInfoResult.errMsg === "saveImageToPhotosAlbum:ok"
                  ) {
                    uni.showToast({
                      title: "已成功保存至相册！",
                      duration: 1000,
                    });
                  } else {
                    uni.showToast({
                      title: "图片保存失败！",
                      duration: 1000,
                    });
                  }
                });
            }
          },
        });
      } else {
        uni
          .authorize({
            scope: "scope.writePhotosAlbum",
          })
          .then(() => {
            uni.getImageInfo({
              src: imageTempPath,
              success(result) {
                if (result.path) {
                  uni
                    .saveImageToPhotosAlbum({
                      filePath: result.path,
                    })
                    .then((getImageInfoResult) => {
                      if (
                        getImageInfoResult.errMsg ===
                        "saveImageToPhotosAlbum:ok"
                      ) {
                        uni.showToast({
                          title: "已成功保存至相册！",
                          duration: 1000,
                        });
                      } else {
                        uni.showToast({
                          title: "图片保存失败！",
                          duration: 1000,
                        });
                      }
                    });
                }
              },
            });
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
  });
};

//uni微信小程序打开Pdf文件
export const wxOpenPdf = (path: string) => {
  console.log("执行打开pdf");

  // uni.downloadFile({
  //   url: path, //这里的path必须是线上链接 需要通过uploadFile上传到服务器
  //   success(res) {
  //     uni.openDocument({
  //       filePath: res.tempFilePath,
  //       fileType: "pdf",
  //       showMenu: true,
  //       success: function () {
  //         uni.showToast({
  //           title: "打开文档成功",
  //         });
  //       },
  //       fail: function () {
  //         uni.showToast({
  //           title: "打开文档失败",
  //         });
  //       },
  //     });
  //   },
  // });
  uni.chooseMessageFile({
    count: 1,
    type: "file",
    success(res) {
      const tempFilePath = res.tempFiles[0].path;
      uni.openDocument({
        filePath: tempFilePath,
        fileType: "pdf",
        showMenu: true,
      });
    },
  });
};

/**
 * @Description: 获取电量
 * @Author: ZhangHan
 * @Date: 2025-08-20 16:27:53
 */
export const getBeary = () => {
  uni.getBatteryInfo({
    success: (res) => {
      console.log(res);
      uni.showToast({
        title: "电量为：" + res?.level + "%",
        duration: 1000,
      });
      return res?.level;
    },
    fail: (err) => {
      console.log(err, "设备暂不支持");
    },
  });
};

/**
 * @Description: 获取页面传参
 * @Author: ZhangHan
 * @Date: 2025-08-20 17:58:03
 */
export const getCurrentRouteParams = () => {
  const pages = getCurrentPages();
  const currentPage: any = pages[pages.length - 1];
  return currentPage?.options;
};

/**
 * @Description: 是否大写字母
 * @Author: ZhangHan
 * @Date: 2025-08-27 15:04:03
 * @param {string} char
 */
export function isUpperCaseChar(char: string) {
  return char === char.toUpperCase();
}

/**
 * @Description: 是否小写字母
 * @Author: ZhangHan
 * @Date: 2025-08-27 15:04:15
 * @param {string} char
 */
export function isLowerCaseChar(char: string) {
  return char === char.toLowerCase();
}

/**
 * @Description: 获取Picker数据
 * @Author: ZhangHan
 * @Date: 2025-08-29 15:41:22
 * @param {any} data
 */
export const getPickerData = (data: any) => {
  const options: { text: string; value: string }[] = [];
  Object.getOwnPropertyNames(data).map((item) =>
    options.push({
      text: data[item]?.text,
      value: item,
    })
  );
  return options;
};


//form重置字段,uniui的resetFields方法不生效
export const resetForm = (form: any) => {
  Object.keys(form).forEach((key) => {
    form[key] = undefined;
  });
};

/**
 * @Description:  生成一个 0 到 length - 1 之间的随机整数
 * @Author: ZhangHan
 * @Date: 2025-09-05 16:04:39
 * @param {Array} arr
 */
export function getRandomIndex(arr:Array<any>) {
    // 获取数组的长度
    const length = arr.length;
    // 生成一个 0 到 length - 1 之间的随机整数
    const randomIndex = Math.floor(Math.random() * length);
    return randomIndex;
}